library(ggplot2)

# 查看 BMI 列名（确保一致）
colnames(sv$S)  

# 提取绘图数据
plot_data <- data.frame(
  BMI_value = sv$X$BMI,
  SHAP_value = sv$S[, "BMI"]
)

# 绘制英文版依赖图
p <- ggplot(plot_data, aes(x = BMI_value, y = SHAP_value, color = BMI_value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for BMI",           # 英文标题
    x = "BMI (kg/m²)",                                # X轴标签
    y = "SHAP value (Contribution to malnutrition risk)", # Y轴标签
    color = "BMI"                                     # 图例标题
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    legend.title = element_text(size = 10)
  )

# 显示
print(p)

library(ggplot2)

# 设置年龄列名（改成你数据中实际的中文列名）
age_col <- "年龄"   # 请确保跟 colnames(sv$S) 显示的一致

# 提取绘图数据
plot_data_age <- data.frame(
  Age_value = sv$X[[age_col]],          # 年龄原始值
  SHAP_value = sv$S[, age_col]          # 年龄对应的SHAP贡献值
)

# 绘制英文版依赖图（图表标签为英文，但横轴显示数据原文）
p_age <- ggplot(plot_data_age, aes(x = Age_value, y = SHAP_value, color = Age_value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for Age",
    x = "Age (years)",                                # 横轴英文标签
    y = "SHAP value (Contribution to malnutrition risk)",
    color = "Age"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    legend.title = element_text(size = 10)
  )

# 显示图形
print(p_age)



feature_col <- "三个月体重下降"  

plot_data_wl <- data.frame(
  value = sv$X[[feature_col]],
  shap = sv$S[, feature_col]
)

p_wl <- ggplot(plot_data_wl, aes(x = value, y = shap, color = value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for 3-Month Weight Loss",
    x = "Weight loss (3 months)",
    y = "SHAP value (Contribution to malnutrition risk)",
    color = "Weight loss"
  ) +
  theme_minimal(base_size = 14) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))

print(p_wl)

feature_col <- "手术类型"  

plot_data_surgery <- data.frame(
  value = sv$X[[feature_col]],
  shap = sv$S[, feature_col]
)

p_surgery <- ggplot(plot_data_surgery, aes(x = value, y = shap, color = value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for Surgery Type",
    x = "Surgery Type (severity score)",
    y = "SHAP value (Contribution to malnutrition risk)",
    color = "Surgery Type"
  ) +
  theme_minimal(base_size = 14) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))

print(p_surgery)

plot_data_pn_num <- data.frame(
  value = sv$X[[feature_col]],
  shap = sv$S[, feature_col]
)

p_pn_num <- ggplot(plot_data_pn_num, aes(x = value, y = shap, color = value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for Parenteral Nutrition Duration",
    x = "Parenteral Nutrition (days/dose)",
    y = "SHAP value (Contribution to malnutrition risk)",
    color = "PN value"
  ) +
  theme_minimal(base_size = 14) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"))

print(p_pn_num)

feature_col <- "血红蛋白"  

plot_data_hb <- data.frame(
  value = sv$X[[feature_col]],
  shap = sv$S[, feature_col]
)

p_hb <- ggplot(plot_data_hb, aes(x = value, y = shap, color = value)) +
  geom_point(size = 1.8, alpha = 0.7) +
  scale_color_gradient(low = "blue", high = "red") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "darkgrey") +
  labs(
    title = "SHAP Dependence Plot for Hemoglobin",
    x = "Hemoglobin (g/L)",
    y = "SHAP value (Contribution to malnutrition risk)",
    color = "Hb"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    legend.title = element_text(size = 10)
  )

print(p_hb)

# ---------- 挑选典型患者 ----------
mal_id <- which(Ttrain$营养不良风险 == 1)[1]     # 第一个营养不良患者
normal_id <- which(Ttrain$营养不良风险 == 0)[1]   # 第一个正常患者

# ---------- 瀑布图（营养不良） ----------
pred_prob <- predict(rfcla, newdata = X_train[mal_id, , drop = FALSE], type = "prob")[, "1"]

p_waterfall <- sv_waterfall(sv, row_id = mal_id) +
  labs(
    title = "Features of patient with malnutrition",
    subtitle = paste("Predicted probability:", round(pred_prob, 3))
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5)
  )

ggsave("figure_6a_waterfall.png", p_waterfall, width = 10, height = 6, dpi = 300)

# ---------- 水平条形图（正常个体） ----------
shap_single <- sv$S[normal_id, ]
features_single <- sv$X[normal_id, ]

plot_df <- data.frame(
  feature = names(shap_single),
  shap = as.numeric(shap_single),
  value = sapply(features_single, function(x) {
    if (is.factor(x)) as.character(x) else round(as.numeric(x), 2)
  })
)

# 筛选贡献明显的特征（SHAP绝对值 > 0.001）
plot_df <- plot_df[abs(plot_df$shap) > 0.001, ]

# 按SHAP值排序
plot_df <- plot_df[order(plot_df$shap), ]
plot_df$feature <- factor(plot_df$feature, levels = plot_df$feature)

p_bar <- ggplot(plot_df, aes(x = feature, y = shap, fill = shap > 0)) +
  geom_bar(stat = "identity", width = 0.7) +
  coord_flip() +
  scale_fill_manual(values = c("lightblue", "#D7191C"), guide = FALSE) +
  labs(
    title = "Features of an individual with normal nutrition",
    x = NULL,
    y = "SHAP value (Contribution to malnutrition risk)"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.y = element_text(size = 10)
  )

# 在条形末端添加特征值标签
p_bar <- p_bar + 
  geom_text(
    aes(label = as.character(value), 
        hjust = ifelse(shap > 0, -0.1, 1.1)),
    size = 3.5, color = "black"
  )

ggsave("figure_6b_bar.png", p_bar, width = 10, height = 6, dpi = 300)

# 预览
print(p_waterfall)
print(p_bar)

# 1. 中英文映射表（必须覆盖所有特征）
feature_map <- c(
  "BMI" = "BMI",
  "年龄" = "Age",
  "三个月体重下降" = "Weight loss (3 months)",
  "手术类型" = "Surgery type",
  "肠外营养" = "Parenteral nutrition",
  "血红蛋白" = "Hemoglobin",
  "GNRI" = "GNRI",
  "白蛋白" = "Albumin",
  "中性粒" = "Neutrophils",
  "肠内营养" = "Enteral nutrition"
  # 请按需补充其他特征
)
to_english <- function(x) ifelse(x %in% names(feature_map), feature_map[x], x)

# 2. 挑选典型患者
mal_id <- which(Ttrain$营养不良风险 == 1)[1]     # 营养不良
normal_id <- which(Ttrain$营养不良风险 == 0)[1]   # 正常

# 3. —— 瀑布图（红蓝配色）
pred_prob <- predict(rfcla, newdata = X_train[mal_id, , drop = FALSE], type = "prob")[, "1"]

p_waterfall <- sv_waterfall(
  sv, 
  row_id = mal_id, 
  format_feat = to_english,
  fill_colors = c("#D7191C", "#2C7BB6")  # 正向=红色，负向=蓝色
) +
  labs(
    title = "Features of patient with malnutrition",
    subtitle = paste("Predicted probability:", round(pred_prob, 3))
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5)
  )

# 4. —— 水平条形图（红蓝配色）
shap_single <- sv$S[normal_id, ]
features_single <- sv$X[normal_id, ]

plot_df <- data.frame(
  feature = names(shap_single),
  shap = as.numeric(shap_single),
  value = sapply(features_single, function(x) {
    if (is.factor(x)) as.character(x) else round(as.numeric(x), 2)
  })
)
plot_df$feature <- sapply(plot_df$feature, to_english)
plot_df <- plot_df[abs(plot_df$shap) > 0.001, ]
plot_df <- plot_df[order(plot_df$shap), ]
plot_df$feature <- factor(plot_df$feature, levels = plot_df$feature)

p_bar <- ggplot(plot_df, aes(x = feature, y = shap, fill = shap > 0)) +
  geom_bar(stat = "identity", width = 0.7) +
  coord_flip() +
  scale_fill_manual(
    values = c("TRUE" = "#D7191C", "FALSE" = "#2C7BB6"),  # 正向红色，负向蓝色
    guide = FALSE
  ) +
  labs(
    title = "Features of an individual with normal nutrition",
    x = NULL,
    y = "SHAP value (Contribution to malnutrition risk)"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.y = element_text(size = 10)
  ) +
  geom_text(
    aes(label = as.character(value), 
        hjust = ifelse(shap > 0, -0.1, 1.1)),
    size = 3.5, color = "black"
  )

# 5. 保存并显示
ggsave("figure_6a_waterfall.png", p_waterfall, width = 10, height = 6, dpi = 300)
ggsave("figure_6b_bar.png", p_bar, width = 10, height = 6, dpi = 300)

print(p_waterfall)
print(p_bar)

